package com.mnf.server.component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.handler.AbstractHandler;

import com.mnf.server.ServerConstants;
import com.mnf.utils.StringUtils;

public abstract class AbstractMusicHttpServerHandler extends AbstractHandler {
	

	@Override
	public void handle(String target, org.eclipse.jetty.server.Request baseRequest,
			HttpServletRequest httpRequest, HttpServletResponse httpResponse)
			throws IOException, ServletException {		
		if (httpRequest.getRequestURL().toString().contains(ServerConstants.GET_INFO_REQUEST)) {
			httpResponse.setContentType("text/html;charset=utf-8");
			httpResponse.setStatus(HttpServletResponse.SC_OK);
			baseRequest.setHandled(true);
			httpResponse.getWriter().println("<h1>This is a music player server</h1>");
			
		} else if (httpRequest.getRequestURL().toString().contains(ServerConstants.COMMAND_REQUEST)) {
			String playCommand = httpRequest.getParameter(ServerConstants.PLAY_COMMAND);
			String stopCommand = httpRequest.getParameter(ServerConstants.STOP_COMMAND);
			String gotoTimeCommand = httpRequest.getParameter(ServerConstants.GOTO_TIME);
			String volumeToCommand = httpRequest.getParameter(ServerConstants.VOLUME_TO);
			
			if (StringUtils.isNotEmpty(playCommand)) {
				int play = Integer.parseInt(playCommand);
				onPlayRequestCommand((play == 1), httpResponse);
				baseRequest.setHandled(true);
			} else if (StringUtils.isNotEmpty(stopCommand)) {
				int stop = Integer.parseInt(stopCommand);
				onStopRequestCommand((stop == 1), httpResponse);
			} else if (StringUtils.isNotEmpty(gotoTimeCommand)) {
				SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
				Date time = null;
				try {
					time = formatter.parse(gotoTimeCommand);
				} catch (ParseException e) {
					System.err.println(e.getMessage());
				}
				if (time != null) {
					onGotoTimeRequestCommand(time, httpResponse);					
				}
			} else if (StringUtils.isNotEmpty(volumeToCommand)) {
				int volume = Integer.parseInt(volumeToCommand);
				onVolumeTimeRequestCommand(volume, httpResponse);
			}
		}
	}
	
	protected abstract void onPlayRequestCommand(boolean play, HttpServletResponse httpResponse) throws IOException;
	protected abstract void onStopRequestCommand(boolean stop, HttpServletResponse httpResponse);
	protected abstract void onGotoTimeRequestCommand(Date time, HttpServletResponse httpResponse);
	protected abstract void onVolumeTimeRequestCommand(int volume, HttpServletResponse httpResponse);
	
	
}
